<template>
  <div class="cart-container">
    <div class="header">
      <el-button type="primary" @click="handleBatchDelete">批量删除</el-button>
      <el-button type="success" @click="handleCheckout">结算</el-button>
    </div>
    <div style="width: 100%" v-if="state.cartItems.length  > 0">
      <el-card v-for="item in state.cartItems" class="cart-item" style="margin-bottom: 20px;">
        <el-row>
          <el-col :span="2">
            <el-checkbox v-model="item.checked" @change="handleCheckChange(item)"></el-checkbox>
          </el-col>
          <el-col :span="4">
            <el-image :src="item.medicines.medicineImg" style="width: 80px; height: 80px" fit="cover"/>
          </el-col>
          <el-col :span="14">
            <div>
              <div>{{ item.medicines.medicineName }}</div>
              <div>单价：￥{{ item.medicines.price }}</div>
              <div>积分单价：{{ item.medicines.point }}</div>
              <div>
                <el-input-number v-model="item.medicineCount" disabled/>
              </div>
            </div>
          </el-col>
          <el-col :span="4">
            <el-button type="danger" @click="deleteCartItem(item.cartId)">删除</el-button>
          </el-col>
        </el-row>
      </el-card>
    </div>
    <div v-else>
      <el-empty description="暂无数据"/>
    </div>
    <!-- 添加分页控件 -->
    <el-pagination
        style="margin-top: 20px; text-align: center;"
        background
        layout="prev, pager, next"
        :total="state.total"
        :page-size="state.pageSize"
        :current-page="state.currentPage"
        :page-count="state.pages"
        @current-change="handlePageChange"
    />
    <!-- 结算确认弹窗 -->
    <el-dialog
        v-model="isCheckoutDialogVisible"
        title="结算确认"
        :close-on-click-modal="false"
    >
      <span>请选择结算方式</span>
      <el-form>
        <el-form-item label="配送方式">
          <el-radio-group v-model="deliveryType">
            <el-radio label="delivery">配送</el-radio>
            <el-radio label="pickup">自提</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="选择地址" v-show="deliveryType == 'delivery'">
          <el-select v-model="selectedAddress" placeholder="请选择地址">
            <el-option
                v-for="address in addressList"
                :key="address.addressId"
                :label="address.address"
                :value="address.addressId"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button type="primary" @click="handlePointCheckout">积分结算</el-button>
        <el-button @click="handleCashCheckout">现金结算</el-button>
      </template>
    </el-dialog>

    <!-- 现金支付二维码弹窗 -->
  </div>
</template>

<script setup>
import {ref, computed, onMounted, reactive} from 'vue';
import axios from 'axios'; // 假设使用axios来发送HTTP请求
import {ElMessage, ElMessageBox} from 'element-plus';
import {deleteCart, deleteBatchCart, getCartList} from "@/api/shopCart";
import {getAllAddress} from "@/api/userAddress";
import {createOrder, createOrderCash} from "@/api/order";

const state = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0, // 总条数
  pages: 1,
  cartItems: []
});

const isClearDialogVisible = ref(false);
const isCheckoutDialogVisible = ref(false);
const selectedIds = ref([]);
const addressList = ref([]);
const selectedAddress = ref(null);
const deliveryType = ref('delivery'); // 默认选择配送方式

// 新增计算属性，计算选中商品的总积分
const totalPoints = computed(() => {
  const selectedItems = state.cartItems.filter(item => item.checked);
  // 遍历selctedItems，计算出选中商品的总积分
  let totalPoints = 0;
  for (const item of selectedItems) {
    totalPoints += item.medicines.point * item.medicineCount;
  }
  return totalPoints;
});
// 计算总价格
const totalPrice = computed(() => {
  const selectedItems = state.cartItems.filter(item => item.checked);
  // 遍历selctedItems，计算出选中商品的总价格
  let totalPrice = 0;
  for (const item of selectedItems) {
    totalPrice += item.medicines.price * item.medicineCount;
  }
  return totalPrice;
});
const clearCart = () => {
  isClearDialogVisible.value = true;
}

onMounted(() => {
  getCartList({
    current: state.currentPage,
    size: state.pageSize
  }).then(response => {
    console.log('获取购物车数据成功', response.data.data)
    state.cartItems = response.data.data.records.map(item => ({
      ...item,
      checked: false
    }));
    state.total = response.data.data.total;
    state.currentPage = response.data.data.current;
  }).catch(error => {
    console.error('获取购物车数据失败:', error);
    ElMessage.error('获取购物车数据失败');
  })
})

const deleteCartItem = (id) => {
  console.log('删除购物车商品', id);
  deleteCart(id).then(response => {
    console.log('删除购物车商品成功', response.data);
    ElMessage.success('删除购物车商品成功');
    getCartList({
      current: state.currentPage,
      size: state.pageSize
    }).then(response => {
      console.log('获取购物车数据成功', response.data.data)
      state.cartItems = response.data.data.records.map(item => ({
        ...item,
        checked: false
      }));
    })


  })
}

const handleCheckChange = (item) => {
  console.log('选中状态改变', item);
}

const handleBatchDelete = () => {
  const selectedItems = state.cartItems.filter(item => item.checked);
  console.log("selectItems", selectedItems)
  if (selectedItems.length === 0) {
    ElMessage.warning('请选择要删除的商品');
    return;
  }
  const ids = selectedItems.map(item => item.cartId);
  deleteBatchCart(ids).then(response => {
    console.log('批量删除成功', response.data);
    ElMessage.success('批量删除成功');
    getCartList({
      current: state.currentPage,
      size: state.pageSize
    }).then(response => {
      console.log('获取购物车数据成功', response.data.data)
    })
  })

}

const handleCheckout = () => {
  const selectedItems = state.cartItems.filter(item => item.checked);
  if (selectedItems.length === 0) {
    ElMessage.warning('请选择要结算的商品');
    return;
  }
  selectedIds.value = selectedItems.map(item => item.cartId);
  // 获取地址列表
  getAllAddress().then(response => {
    addressList.value = response.data.data;
    isCheckoutDialogVisible.value = true;
  }).catch(error => {
    console.error('获取地址数据失败:', error);
    ElMessage.error('获取地址数据失败');
  });
}

const handlePointCheckout = () => {
  // 组织生成订单的数据
  console.log('selectedIds', selectedIds.value)
  if (deliveryType.value === 'delivery' && !selectedAddress.value) {
    ElMessage.warning('请选择收货地址');
    return;
  }
  // 获取用户信息
  const userInfo = JSON.parse(localStorage.getItem('userInfo'));
  if (!userInfo) {
    ElMessage.warning('请先登录');
    return;
  }
  // 判断用户的积分是否足够
  if (totalPoints.value > userInfo.userPoint) {
    ElMessage.warning('您的积分不足，请选择其他商品');
    return;
  }
  // 积分足够，调用结算方法
  if (deliveryType.value === 'delivery') {
    deliveryType.value = 0;
  }
  const params = {
    cartIds: selectedIds.value,
    totalType: 0,
    giveType: deliveryType.value,
    addressId: 0,
    totalPoint: totalPoints.value
  };
  console.log('params', params);
  if (deliveryType.value === 0) {
    params.addressId = selectedAddress.value;
  }
  createOrder(params).then(response => {
    console.log('积分结算成功', response.data);
    ElMessage.success('积分结算成功');
    isCheckoutDialogVisible.value = false;
    // 结算成功后刷新购物车数据
    getCartList({
      current: state.currentPage,
      size: state.pageSize
    }).then(response => {
      console.log('获取购物车数据成功', response.data.data)
    })
  }).catch(error => {
    console.error('积分结算失败:', error);
    ElMessage.error('积分结算失败');
  })
}

const handleCashCheckout = () => {
  // 组织生成订单的数据
  console.log('selectedIds', selectedIds.value)
  if (deliveryType.value === 'delivery' && !selectedAddress.value) {
    ElMessage.warning('请选择收货地址');
    return;
  }
  // 获取用户信息
  const userInfo = JSON.parse(localStorage.getItem('userInfo'));
  if (!userInfo) {
    ElMessage.warning('请先登录');
    return;
  }
  // 判断用户的现金是否足够
  if (totalPrice.value > userInfo.userMoney) {
    ElMessage.warning('您的余额不足，请及时充值');
    return;
  }
  // 积分足够，调用结算方法
  if (deliveryType.value === 'delivery') {
    deliveryType.value = 0;
  } else {
    deliveryType.value = 1;
  }
  const params = {
    cartIds: selectedIds.value,
    totalType: 1,
    giveType: deliveryType.value,
    addressId: 0,
    totalPrice: totalPrice.value
  };
  console.log('params', params);
  if (deliveryType.value === 0) {
    params.addressId = selectedAddress.value;
  }
  createOrderCash(params).then(response => {
    console.log('现金结算成功', response.data);
    ElMessage.success('现金结算成功');
    isCheckoutDialogVisible.value = false;
    // 结算成功后刷新购物车数据
    getCartList({
      current: state.currentPage,
      size: state.pageSize
    }).then(response => {
      console.log('获取购物车数据成功', response.data.data)
    })
  }).catch(error => {
    console.error('积分结算失败:', error);
    ElMessage.error('积分结算失败');
  })
}

const handlePageChange = (currentPage) => {
  state.currentPage = currentPage;
  getCartList({
    current: state.currentPage,
    size: state.pageSize
  }).then(response => {
    console.log('获取购物车数据成功', response.data.data)
    state.cartItems = response.data.data.records.map(item => ({
      ...item,
      checked: false
    }));
    state.total = response.data.data.total;
    state.currentPage = response.data.data.current;
  }).catch(error => {
    console.error('获取购物车数据失败:', error);
    ElMessage.error('获取购物车数据失败');
  })
}

</script>


<style scoped>
.cart-container {
  max-width: 800px;
  margin: 20px auto;
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.medicine-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  gap: 20px;
}

.clear-btn {
  background: #ff4d4f;
  color: white;
  border: none;
  padding: 5px 10px;
  border-radius: 5px;
  cursor: pointer;
}

.clear-btn:hover {
  background: #ff7875;
}

.product-image {
  width: 80px;
  height: 80px;
  margin-left: 10px;
  border-radius: 10px;
  display: flex;
  flex-direction: column;
  align-content: center;
}

.checkout-btn {
  background: #ff5000;
  color: white;
  padding: 10px 30px;
  border: none;
  border-radius: 20px;
  cursor: pointer;
}

.checkout-btn:hover {
  background: #e64700;
}

.cart-item {
  margin-bottom: 20px;
  background: white;
  border-radius: 8px;
  overflow: hidden;
}

.product-image {
  width: 80px;
  height: 80px;
  margin-left: 10px;
  border-radius: 10px;
  display: flex;
  flex-direction: column;
  align-content: center;
}

.checkout-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 20px;
}
</style>
